package com.qf.fmall2203.orders.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2203.index.entity.Product;
import com.qf.fmall2203.index.entity.ProductImg;
import com.qf.fmall2203.index.productsku.entity.ProductSkus;
import com.qf.fmall2203.index.productsku.service.IProductSkuService;
import com.qf.fmall2203.index.service.ProductImgService;
import com.qf.fmall2203.index.service.ProductService;
import com.qf.fmall2203.odder.entity.ShoppingCart;
import com.qf.fmall2203.odder.service.IShoppingCartService;
import com.qf.fmall2203.orders.entity.OrderItem;
import com.qf.fmall2203.orders.entity.Orders;
import com.qf.fmall2203.orders.mapper.OrdersMapper;
import com.qf.fmall2203.orders.service.IOrderItemService;
import com.qf.fmall2203.orders.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2203.weixin.WxpayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author ljc
 * @since 2023-02-16
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    IShoppingCartService shoppingCartService;
    @Autowired
    IProductSkuService productSkuService;
    @Autowired
    ProductImgService productImgService;
    @Autowired
    IOrderItemService orderItemService;
    @Autowired
    ProductService productService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> add(Integer[] cids, Orders orders) throws Exception {
        //1. 查询用户购物车中的对应的商品套餐库存量是否还足够
        // 如果库存够，则继续下单流程；如果库存量不足，直接抛出异常;任何一个商品的库存不足都算失败
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(new QueryWrapper<ShoppingCart>().in("cart_id", cids));

        List<String> skuIds = shoppingCarts.stream().map(ShoppingCart::getSkuId).collect(Collectors.toList());

        Map<String, ProductSkus> sku_id = productSkuService.list(new QueryWrapper<ProductSkus>().in("sku_id", skuIds))
                .stream().collect(Collectors.toMap(ProductSkus::getSkuId, o->o));

        List<String> productId = shoppingCarts.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        Map<String, String> product_id = productService.list(new QueryWrapper<Product>().in("product_id", productId)).stream().collect(Collectors.toMap(Product::getProductId, Product::getProductName));
        ArrayList<String> productNames = new ArrayList<>();

        for (ShoppingCart shoppingCart : shoppingCarts) {

            ProductSkus stock = sku_id.get(shoppingCart.getSkuId());

            int i  = stock.getStock()-(Integer.valueOf(shoppingCart.getCartNum()));

            if (i<0){

                throw new Exception();
            }

        }
        StringBuilder orderProductId = new StringBuilder();

        product_id.forEach((s, s2) -> {
            if (product_id.size()==0){
                orderProductId.append(s2+",");
            }
            orderProductId.append(s2+",");
        });

        //2. 生成唯一的订单编号
        String orderId = UUID.randomUUID().toString().replaceAll("-", "");

        //3. 生成订单主表（orders表）中的数据
        orders.setOrderId(orderId);

        orders.setCreateTime(new Date());

        orders.setUntitled(orderProductId.toString());

        save(orders);
        //4. 生成订单明细表的数据 （OrderItem表）
        // 购物车中有几条数据，订单明细表中就有几条数据

        Map<String, String> itemIds= productImgService.list(new QueryWrapper<ProductImg>().in("item_id", productId).eq("is_main","1"))
                .stream().collect(Collectors.toMap(ProductImg::getItemId,ProductImg::getUrl));
        for (ShoppingCart shoppingCart : shoppingCarts) {
            String itemId = UUID.randomUUID().toString().replaceAll("-", "");

            ProductSkus stock = sku_id.get(shoppingCart.getSkuId());

            String url = itemIds.get(shoppingCart.getProductId());

            productNames.add(shoppingCart.getProductName());

            String productName = product_id.get(shoppingCart.getProductId());

            OrderItem orderItem = new OrderItem(itemId,orderId,shoppingCart.getProductId(),productName,
            url,stock.getSkuId(),stock.getSkuName(),BigDecimal.valueOf(stock.getSellPrice()), Integer.valueOf(shoppingCart.getCartNum()),null,null,null,null);

            orderItemService.save(orderItem);

        }

        //5. 删除用户购物车中的cids对应数据
        shoppingCartService.remove(new QueryWrapper<ShoppingCart>().in("cart_id",Arrays.asList(cids)));

        //6. 跟微信支付平台交互，获取可以支付的url
        String payUrl = WxpayUtils.getPayUrl(orderId);

        String s = WxpayUtils.queryOrder(orderId);
        //7. 组织返回的map数据

        HashMap<String, Object> data = new HashMap<>();

        data.put("orderId",orderId);

        data.put("productNames",productNames);

        data.put("payUrl",payUrl);


        return data;
    }
}
